const axios = require('axios');
const template = require('../../utils/template');
const globalConfig = require('../../config');
const qs = require('querystring');

module.exports = async (ctx) => {
    const category = ctx.params.category;
    console.log('start', ctx.params);

    const categoryListResponse = await axios({
        method: 'get',
        url: `https://api.juejin.cn/tag_api/v1/query_category_briefs`,
        headers: {
            'User-Agent': globalConfig.ua,
            'Referer': `https://juejin.im/welcome/${category}`,
        }
    });

    console.log("categoryListResponse", categoryListResponse)
    const cat = categoryListResponse.data.data.filter((item) => item.category_url === category)[0];
    // const id = cat.id;
    var data = JSON.stringify({
        "id_type": 2,
        "sort_type": 200,
        "cate_id": `${cat.category_id}`,
        "cursor": "0",
        "limit": 20
    });
    var config = {
        method: 'post',
        url: 'https://api.juejin.cn/recommend_api/v1/article/recommend_cate_feed',
        headers: {
            'Content-Type': 'application/json'
        },
        data: data
    };

    /*
      await axios(config)
        .then(function (response) {
          console.log(JSON.stringify(response.data));
        })
        .catch(function (error) {
          console.log(error);
        });
    */

    const rssListResponse = await axios(config);
    // console.log("idResponse", idResponse.data)


    const responseData = rssListResponse.data;

    ctx.body = template({
        title: `掘金`,
        link: `https://juejin.cn/${category}`,
        description: `掘金`,
        item: responseData.data && responseData.data && responseData.data.map((item) => ({
            title: item.article_info.title,
            description: `${(item.article_info.brief_content || '无描述').replace(/[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f]/g, '')}`,
            pubDate: new Date(parseInt(item.article_info.ctime) * 1000).toUTCString(),
            link: 'https://juejin.cn/post/' + item.article_id
        })),
    });
};